<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * http://featherphp.googlecode.com/
 * 
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */

require_once APP.'config'.DS.'locales.php';

/**
 * Configures the locale.
 */
class LocaleComponent extends Locales
{
	public $lang;
	
	function startup(Controller $Controller)
	{
		# timezone
		$tz = isset($_SESSION['User.timezone']) ? $_SESSION['User.timezone'] : Core::locale_timezone;
		date_default_timezone_set($tz);
		
		# language
		/*
		if (isset($_REQUEST':lang'])) {
			$lang = $_REQUEST['lang'];
		}
		if (empty($lang) and isset($_SESSION['User.lang'])) {
			$lang = $_SESSION['User.lang'];
		}
		if (empty($lang)) {
			$lang = $this->autodetect();
		}
		$this->set($lang);
		*/
		$this->set(Core::locale_default);
	}
	
	/**
	 * Sets the locale.
	 * 
	 * @param $lang String
	 */
	function set($lang)
	{
		$this->lang = empty($this->locales[$lang]) ? Core::locale_default : $lang;
		Core::$locale = $this->locales[$this->lang];
		
		# locale
		putenv("LANG=".Core::$locale);
		setlocale(LC_ALL, Core::$locale.'.'.Core::charset);
		setlocale(LC_NUMERIC, 'C');
		
		# translations (gettext)
#		bindtextdomain('messages', APP.'locale'.DS); 
#		textdomain('messages');
	}
	
	/**
	 * Returns the current locale.
	 * 
	 * @return String
	 */
	function get()
	{
		return $this->locales[$this->lang];
	}
	
	/**
	 * Returns the currently available languages.
	 * 
	 * @return Array
	 * @deprecated Use $Locale->languages directly.
	 */
	function & get_languages()
	{
		/*
		$langs = array();
		foreach($this->languages as $code => $lang)
		{
			if (file_exists(APP.'locale'.DS.$this->locales[$code].DS.'LC_MESSAGES'.DS.'messages.mo')) {
				$langs[$code] = $lang;
			}
		}
		return $langs;
		*/
		return $this->languages;
	}
	
	/**
	 * Autodetect the locale from HTTP headers.
	 * 
	 * @return String
	 */
	function autodetect()
	{
		$accepts = env('HTTP_ACCEPT_LANGUAGE');
		$accepts = explode(',', $accepts);
		
		foreach($accepts as $lang)
		{
			$pos = strpos($lang, ';q=');
			if ($pos)
				$lang = substr($lang, 0, $pos);
			if (isset($this->locales[$lang]))
				return $lang;
		}
		return null;
	}
}
?>